﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using NPOI.SS.Formula.Functions;
using Serilog;
using Serilog.Core;
using SimpleTool.Server;
using SimpleTool.TransformComponent;

namespace SimpleTool.ActivityUnit.EchoControl
{
    /// <summary>
    /// TestStatisticialTree.xaml 的交互逻辑
    /// </summary>
    public partial class TestStatisticialTree : EnjoyWindow
    {
        private ActivityViewModel? viewmodel;

        public TestStatisticialTree()
        {
            Owner = Application.Current.MainWindow;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            InitializeComponent();
            App MyApp = (App)Application.Current;
            viewmodel = MyApp.ServiceProvider.GetRequiredService<ActivityViewModel>();
            DataContext = viewmodel;
            Closed += ClosedEcent;
        }

        private void ClosedEcent(object? sender, EventArgs e)
        {
            if (DataContext is ActivityViewModel ViewModel)
            {
                ViewModel.HoldTestStatisticialTrees.Clear();
                ViewModel.HoldTestStatisticialTotal.Clear();
                TreeViewSelf.Resources.Clear();
                TreeViewSelf.ItemsSource = null;
                TreeViewSelf.ItemTemplate = null;
                TreeViewSelf.Items.Clear();
                ClearAllBindings(this);
                DataContext = null;
                viewmodel = null;
                Serilog.Log.Logger.Print(RuntimeLog.LogType.Debug, "关闭了");
            }
            Closed -= ClosedEcent;
        }

        private void ClearAllBindings(DependencyObject obj)
        {
            if (obj == null) return;

            // 清理绑定
            BindingOperations.ClearAllBindings(obj);

            // 递归清理子元素
            int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                ClearAllBindings(child);
            }
        }

        private void TreeViewSelf_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            object TreeItem = TreeViewSelf.SelectedItem;

            if (DataContext is ActivityViewModel ViewModel)
            {
                if (ViewModel.CmdProductTree.CanExecute(TreeItem))
                {
                    ViewModel.CmdProductTree.Execute(TreeItem);
                }
            }
        }
    }

}
